//
//  RABookrackController.m
//  ReadApp
//
//  Created by 飞猪 on 2018/11/4.
//  Copyright © 2018年 Facebook. All rights reserved.
//

#import "RABookrackController.h"
#import "RABookrackCell.h"
#import "RABookrackRecommendCell.h"
#import "RABookrackTopView.h"
#import "RABookDetailController.h"
#import "RABookrackBottomView.h"
#import "RCTEntryViewController.h"

@interface RABookrackController () <
UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout
>

#pragma mark - 数据源
@property (nonatomic, strong) NSMutableArray<NSMutableArray *> *dataSources;

@property (nonatomic, strong) NSMutableArray<RABookFaceModel *> *topImgs;

@property (nonatomic, strong) NSMutableArray<RABookDetailModel *> *bottomImgs;

@property (nonatomic, strong) NSArray *dataArray; // 轮播图数据源

#pragma mark - 控件
@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) RABookrackTopView *v;

@end

@implementation RABookrackController

- (void)viewDidLoad {
    [super viewDidLoad];
  
  [self creatView];
  
  [self requestForChapterList:@"124"];
  [self requestForChapterList:@"129"];
  
  [self getCacheData];
  
  [self addNoti];
  
  self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarClick)];
  [self.navigationItem.rightBarButtonItem setTintColor:[UIColor whiteColor]];
  [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14.f]} forState:UIControlStateNormal];
}

- (void)addNoti {
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getCacheData) name:AddNativeBookCacheNOti object:nil];
}

- (void)removeNoti {
  [[NSNotificationCenter defaultCenter] removeObserver:self name:AddNativeBookCacheNOti object:nil];
}

- (void)viewWillLayoutSubviews {
  [super viewWillLayoutSubviews];
}

- (void)dealloc {
  [self removeNoti];
}

- (void)creatView {
  
  self.view.backgroundColor = [UIColor whiteColor];
  
  [self.view addSubview:self.collectionView];
  [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.edges.mas_equalTo(self.view);
  }];
  
}

- (void)getCacheData {
  
  NSArray *models = [RABookDetailModel zxg_selectAll];
  [self.bottomImgs removeAllObjects];
  if (models && models.count > 0) {
    [self.bottomImgs addObjectsFromArray:models];
  }
  [self.collectionView reloadData];
}

- (void)refreshView:(NSArray<RABookFaceModel *> *)models {
  
  [self.dataSources.firstObject addObjectsFromArray:models];
  [self.collectionView reloadData];
  
}

#pragma mark - Event
- (void)longPress {
  
  for (RABookDetailModel *model in self.bottomImgs) {
    model.isDelegate = !model.isDelegate;
  }
  [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:1]];
  
}

- (void)delete:(RABookDetailModel *)model {
  
  [self.bottomImgs removeObject:model]; // 移除内存
  [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:1]];
  
  // 移除数据库
  BOOL res = [RABookDetailModel zxg_deleteObjWithConditionStr:[NSString stringWithFormat:@"where bookId = %@", model.bookId]];
  if (res) {
    [self.view makeToast:@"移除成功"];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:RemoveNativeBookCacheNOti object:nil];
  }
  
}

- (void)rightBarClick {
  RCTEntryViewController *ctrl = [[RCTEntryViewController alloc] init];
  ctrl.router = @"SearchList";
  [self.navigationController pushViewController:ctrl animated:YES];
}

#pragma mark - Network
- (void)requestForChapterList:(NSString *)uId {
  
  NSDictionary *params = @{
                           @"id": uId ?: @"124"
                           };
  [SVProgressHUD showWithStatus:@"加载中..."];
  [SVProgressHUD setFont:[UIFont boldSystemFontOfSize:14.f]];
  [SVProgressHUD setForegroundColor:[UIColor grayColor]];
  [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
  [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
  [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeNative];
  
  [RDNetworkTool requestForBookFaceList:params successBlock:^(NSArray<RABookFaceModel *> *models) {
      [SVProgressHUD dismiss];
    
    RABookFaceModel *model = [models firstObject];
    if (model) {
      
      if ([uId isEqualToString:@"124"]) {
        [self refreshView:model.children];
      }
      else {
        self.v.models = model.children;
      }
    }
    
  } failBlock:^(NSString *errorMsg) {
    [SVProgressHUD dismiss];
    [SVProgressHUD showErrorWithStatus:errorMsg];
  }];
  
}

#pragma mark - UICollectionViewDelegate, UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
  return self.dataSources.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
  
  return [self.dataSources objectAtIndex:section].count;
  
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  
  if (indexPath.section == 0) {
    RABookrackRecommendCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass(RABookrackRecommendCell.class) forIndexPath:indexPath];
    RABookFaceModel *model = [[self.dataSources objectAtIndex:indexPath.section] objectAtIndex:indexPath.item];
    model.place = indexPath.item;
    cell.model = model;
    return cell;
  }
  else {
    RABookrackCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass(RABookrackCell.class) forIndexPath:indexPath];
    cell.detailModel = [[self.dataSources objectAtIndex:indexPath.section] objectAtIndex:indexPath.item];
    @weakify(self)
    [cell setLongPressCallback:^{
      @strongify(self)
      [self longPress];
    }];
    [cell setDeleteCallback:^(RABookDetailModel *model) {
      @strongify(self)
      [self delete:model];
    }];
    return cell;
  }
  
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
  
  if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {

      RABookrackTopView *v = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass(RABookrackTopView.class) forIndexPath:indexPath];
    self.v = v;
    
    __weak typeof(RABookrackController *) ws = self;
    [v setJumpToBookDetail:^(RABookFaceModel *model) {
      RABookDetailController *ctrl = [[RABookDetailController alloc] init];
      ctrl.model = model;
      [ws.navigationController pushViewController:ctrl animated:YES];
    }];
    
      return v;
    
  }
  else if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
    
    if (self.bottomImgs.count == 0) {
      RABookrackBottomView *v = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:NSStringFromClass(RABookrackBottomView.class) forIndexPath:indexPath];
      return v;
    }
  }
  
  return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
  
    if (section == 0) {
      return CGSizeMake(0, kScreenWidth * 0.6);
    }
    else {
      return CGSizeMake(0, 0);
    }
  
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
  if (section == 0) {
    if (self.bottomImgs.count == 0) {
      return CGSizeMake(0, 88.f);
    }
    
    return CGSizeMake(0, 0);
  }
  else {
    return CGSizeMake(0, 0);
  }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
  
  if (indexPath.section == 0) {
    
    RABookFaceModel *model = [[self.dataSources objectAtIndex:indexPath.section] objectAtIndex:indexPath.item];
    
    RABookDetailController *ctrl = [[RABookDetailController alloc] init];
    ctrl.model = model;
    [self.navigationController pushViewController:ctrl animated:YES];
  }
  else {
    
    RABookDetailModel *detailModel = [[self.dataSources objectAtIndex:indexPath.section] objectAtIndex:indexPath.item];
    
    RABookDetailController *ctrl = [[RABookDetailController alloc] init];
    
    RABookFaceModel *model = [RABookFaceModel new];
    model.name = detailModel.bookName;
    model.toUrl = detailModel.bookId;
    ctrl.model = model;
    [self.navigationController pushViewController:ctrl animated:YES];
    
  }
  
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
  
  if (indexPath.section == 0) {
    CGFloat w = (kScreenWidth) / 3;
    CGFloat h = w * 1.3;
    return CGSizeMake(w, h);
  }
  else {
    CGFloat w = (kScreenWidth - 4 * 10.f) / 3 - 1;
    CGFloat h = w * 1.3;
    return CGSizeMake(w, h);
  }

}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
  if (section == 0) {
    return 0;
  }
  else {
    return 10;
  }
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
  if (section == 0) {
    return 0;
  }
  else {
    return 10;
  }
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
  
  if (section == 0) {
    return UIEdgeInsetsMake(0, 0, 0, 0);
  }
  else {
    return UIEdgeInsetsMake(10, 10, 10, 10);
  }
  
}

#pragma mark - LazyLoad
- (UICollectionView *)collectionView {
  if (!_collectionView) {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    _collectionView.backgroundColor = self.view.backgroundColor;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.bounces = YES;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.showsHorizontalScrollIndicator = NO;
    [_collectionView registerClass:RABookrackCell.class forCellWithReuseIdentifier:NSStringFromClass(RABookrackCell.class)];
    [_collectionView registerClass:RABookrackRecommendCell.class forCellWithReuseIdentifier:NSStringFromClass(RABookrackRecommendCell.class)];
    [_collectionView registerClass:RABookrackTopView.class forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass(RABookrackTopView.class)];
    [_collectionView registerClass:RABookrackBottomView.class forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:NSStringFromClass(RABookrackBottomView.class)];
    
  }
  return _collectionView;
}

- (NSMutableArray<NSMutableArray *> *)dataSources {
  if (!_dataSources) {
    _dataSources = [NSMutableArray array];
    
    [_dataSources addObject:self.topImgs];
    [_dataSources addObject:self.bottomImgs];
  }
  return _dataSources;
}

- (NSMutableArray<RABookFaceModel *> *)topImgs {
  if (!_topImgs) {
    _topImgs = [NSMutableArray array];
  }
  return _topImgs;
}

- (NSMutableArray<RABookDetailModel *> *)bottomImgs {
  if (!_bottomImgs) {
    _bottomImgs = [NSMutableArray array];
  }
  return _bottomImgs;
}

- (NSArray *)dataArray {
  if (!_dataArray) {
    _dataArray = @[@"", @"", @""];
  }
  return _dataArray;
}

#pragma mark - filePath
- (NSString *)cacheFilePath {
  
  NSFileManager *fileManager = [NSFileManager defaultManager];
  NSString *directoryPath = [NSString stringWithFormat:@"%@/StoryCache", [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]];
  if (![fileManager fileExistsAtPath:directoryPath]) {
    [fileManager createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:nil];
  }
  
  return directoryPath;
}

@end
